import * as moment from "moment"
import vue from "vue"


/** 创建编辑新增题目的基本数据 */
interface questionEdit_UtilBase {
  questionType: number
  question: string
  answerOptions: string
  id: string
  DatabaseID?: string
}

class setUtil {
  path: string
  companyId: string
  correct: number
  corpInfo: typeof window.corpInfo | { company: string }
  userInfo: typeof window.userInfo | { company: string }
  /** `/${this.companyId}/instructorAgent` */
  basePath: string
  /** YYYY-MM-DD HH:mm */
  momentFormatStr: string

  constructor() {
    this.path = 'home'
    this.companyId = window.companyId
    this.correct = window.correct
    this.corpInfo = window.corpInfo
    this.userInfo = window.userInfo

    this.basePath = `/${this.companyId}/home`
    this.momentFormatStr = "YYYY-MM-DD HH:mm"
    if (window.permissionError) {
      let reg = window.location.href.match(/(\/\/.{1,}.com\/)(.{1,})(\/home)/)
      if (reg && reg.length >= 4) {
        this.companyId = reg[2]
      }
      this.corpInfo!.company = '英盛网'
      return
    }
    window.corpInfo = null
  }

  /** 获取当前时间的moment对象 */
  getNowMoment() {
    if (this.correct) {
      return moment(Date.now() - this.correct)
    } else {
      return moment()
    }
  }

  /** 格式化时间 YYYY-MM-DD HH:mm */
  momentFormat(data: any) {
    return moment(data).format(this.momentFormatStr)
  }

  /** 编辑/新增--题目模型 */
  questionModel<T extends questionEdit_UtilBase>(question: T) {
    return {
      editStatus: false,
      questionType: question.questionType,
      question: question.question,
      answerOptions: this.parseAnswerOptions(question.answerOptions),
      id: question.id,
      dataBaseId: question.DatabaseID || ''
    }
  }

  /** 编辑/新增--新建题目 */
  newQuestionModel(questionType: number) {
    return {
      editStatus: true,
      question: "",
      questionType: questionType,
      answerOptions: []
    }
  }

  /** 处理问卷题目返回列表
   * extends 继承这个questionModel.questionGroupList 约束
   */
  questionGroup<T extends questionModel.questionGroupList>(questionList: T[], cb?: any) {
    let saveQuestionList: questionModel.questionGroupJson<T> = {}
    let questionGroup: questionModel.questionGroup<T>[] = []
    questionList.forEach(item => {
      if (saveQuestionList[item.questionType] === undefined) {
        saveQuestionList[item.questionType] = {
          typeStr: this.questonType(item.questionType),
          questionType: item.questionType,
          questionsList: []
        };
      }
      item = this.questionFormat(item)
      if (cb) {
        cb(item)
      }
      saveQuestionList[item.questionType].questionsList.push(item);
    });
    for (let key in saveQuestionList) {
      questionGroup.push(saveQuestionList[key])
    }
    questionGroup.sort((a: any, b: any) => {
      return a.questionType - b.questionType;
    });
    return questionGroup
  }

  /** 题目数据格式化 */
  questionFormat<T extends questionModel.questionGroupList>(question: T) {
    question.parseAnswerOptions = this.parseAnswerOptions(question.answerOptions)
    question.formatQuestion = this.blankQuestionReplace(question.question)
    if (question.questionType === 13) {
      question.blankQuestionLength = this.blankQuestionLength(question.question)
    }
    return question
  }

  /** 通过question判断填空题 选项长度 */
  blankQuestionLength(question: string) {
    let blankQuestionLength = 0;
    let leng = question.match(/\(\)/g);
    if (leng) {
      blankQuestionLength = leng.length;
    }
    return blankQuestionLength
  }

  /** 对question中()进行替换，question */
  blankQuestionReplace(question: string) {
    return question.replace(/\(\)/g, "&nbsp;(&nbsp;&nbsp;&nbsp;)&nbsp;");
  }

  /** 解析选项字符 */
  parseAnswerOptions(answerOptions: string) {
    try {
      let parse = JSON.parse(answerOptions)
      return parse.items || parse.Options
    } catch (e) {
      console.error(`题目答案解析出错，${answerOptions}`)
      console.error(e)
    }
  }

  questonType(questionType: number) {
    switch (questionType) {
      case 10:
        return "单选题";
      case 11:
        return "多选题";
      case 12:
        return "判断题";
      case 13:
        return "填空题";
      case 14:
        return "问答题";
      default:
        return "";
    }
  }

  /** 题库类型列表 */
  questonTypeList() {
    return [
      {
        type: 10,
        typeName: "单选题"
      },
      {
        type: 11,
        typeName: "多选题"
      },
      {
        type: 12,
        typeName: "判断题"
      },
      {
        type: 13,
        typeName: "填空题"
      },
      {
        type: 14,
        typeName: "问答题"
      }
    ];
  }

  /** 个人版--判断用户当前问卷状态
   * 0:未生效 1：已完成 2：未完成 3：已失效
   */
  personalSurveyStatus(survey: Psurvey.surveyItem) {
    // 0:未生效 1：已完成 2：未完成 3：已失效
    if (survey.complete === 1) {
      return 1;
    } else {
      let nowMoment = this.getNowMoment()
      if (nowMoment.isAfter(survey.endTime)) {
        return 3;
      } else if (nowMoment.isAfter(survey.startTime)) {
        return 2;
      } else {
        return 0;
      }
    }
  }

  getUrlParams(obj: any) {
    const paramsList = Object.keys(obj).map((key) => {
      const val = obj[key]
      return `${key}=${val === undefined ? '' : encodeURIComponent(val)}`
    })
    const result = `${paramsList.join("&")}`
    return result
  }
}

let util = new setUtil()
export default util
